package com.wencun.cunpicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wencun.cunpicturebackend.enums.SpaceLevelEnum;
import com.wencun.cunpicturebackend.exception.BusinessException;
import com.wencun.cunpicturebackend.exception.ErrorCode;
import com.wencun.cunpicturebackend.exception.ThrowUtils;
import com.wencun.cunpicturebackend.model.dto.space.SpaceAddRequest;
import com.wencun.cunpicturebackend.model.dto.space.SpaceQueryRequest;
import com.wencun.cunpicturebackend.model.entity.Space;
import com.wencun.cunpicturebackend.model.entity.User;
import com.wencun.cunpicturebackend.model.vo.SpaceVO;
import com.wencun.cunpicturebackend.model.vo.UserVO;
import com.wencun.cunpicturebackend.service.SpaceService;
import com.wencun.cunpicturebackend.mapper.SpaceMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author 温存
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-09-06 19:56:31
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {

    private final UserServiceImpl userService;

    public SpaceServiceImpl(UserServiceImpl userService) {
        this.userService = userService;
    }

    @Resource
    private TransactionTemplate transactionTemplate;
    // 使用 ConcurrentHashMap 来存储锁
    private final Map<Long, Object> lockMap = new ConcurrentHashMap<>();

    /**
     * 创建空间
     *
     * @param spaceAddRequest
     * @param loginUser
     * @return long
     * @time 2025-09-08 15:27
     */

    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        Space space = buildInsertSpace(spaceAddRequest, loginUser);
        // 数据校验
        this.validSpace(space, true);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        // 权限校验
        if (SpaceLevelEnum.COMMON.getValue() != spaceAddRequest.getSpaceLevel() && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限创建指定级别的空间");
        }
        Object lock = lockMap.computeIfAbsent(userId, key -> new Object()); // 获取或创建锁对象
        synchronized (lock) { // 在数据库查询和插入之前加锁
            try {

                Long newSpaceId = transactionTemplate.execute(status -> {
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            .exists();
                    ThrowUtils.throwIf(exists, ErrorCode.SYSTEM_ERROR, "用户已存在私有空间");
                    ThrowUtils.throwIf(!this.save(space), ErrorCode.SYSTEM_ERROR, "创建失败");
                    return space.getId();
                });
                return Optional.ofNullable(newSpaceId).orElse(-1L);
            } finally {
                // 防止内存泄漏，确保移除锁
                lockMap.remove(userId);
            }
        }
    }

    private Space buildInsertSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        // 默认值
        if (StrUtil.isBlank(spaceAddRequest.getSpaceName())) {
            space.setSpaceName("默认空间");
        }
        if (spaceAddRequest.getSpaceLevel() == null) {
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        // 填充数据
        this.fillSpaceBySpaceLevel(space);
        return space;
    }

    /**
     * 校验空间是否合法
     *
     * @param space
     * @param add
     * @time 2025-09-06 23:00
     */
    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        if (add) {
            if (StrUtil.isBlank(spaceName)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (spaceLevel == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            }
        }
        // 修改数据时，空间名称进行校验
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
        }
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        // 1. 获取 SpaceVO
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        // 2. 关联查询
        Long userId = spaceVO.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    /**
     * 获取分页空间列表（脱敏）
     * @param spacePage
     * @param request
     * @return Page<SpaceVO>
     * @time 2025-09-08 19:59
     */

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        //如果分页数据为空则返回对应的分页VO
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        //spaceList 转换为 spaceVOList
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo)
                .collect(Collectors.toList());
        //1.关联用户查询信息
        //1.1 收集用户id 1,2,3,4
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId)
                .collect(Collectors.toSet());
        //1.2 关联一起 1 => user1, 2 => user2
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> wrapper = new QueryWrapper<>();
        // 1. 为空直接返回
        if (spaceQueryRequest == null) {
            return wrapper;
        }
        // 2. 取出所有字段
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        // 3. 封装查询条件
        wrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        wrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        wrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        wrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
//        wrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);
        // 4. 排序
        wrapper.orderBy(StrUtil.isNotBlank(sortField), sortOrder.equals("ascend"), sortField);
        // 5. 返回结果
        return wrapper;
    }

    /**
     * 根据空间级别自动填充限额
     *
     * @param space
     * @time 2025-09-06 23:00
     */
    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        // 根据空间级别，自动填充限额
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }

    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        // 仅本人或管理员可编辑
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }


}




